/* eslint-disable @typescript-eslint/no-explicit-any */
// src/utils/request.ts

import axios from 'axios'
import type { AxiosInstance,  AxiosResponse,InternalAxiosRequestConfig } from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserStore } from '@/store/auth'

let loadingInstance: any = null
let requestCount = 0

const startLoading = () => {
  if (requestCount === 0) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
  }
  requestCount++
}

const stopLoading = () => {
  requestCount--
  requestCount = Math.max(requestCount, 0)
  if (requestCount === 0 && loadingInstance) {
    loadingInstance.close()
  }
}
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 10000,
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    startLoading()
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    if (config.url?.startsWith('/goapi')) {
      config.baseURL = import.meta.env.VITE_API_BASE_URL.replace('/adminapi', '')
    }
    return config
  },
  (error) => {
    stopLoading()
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    stopLoading()
    const res = response.data
    if (res.code === 401) {
      useUserStore().logout()
      return Promise.reject(new Error('未授权'))
    }
    if (res.code !== 200) {
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    return res
  },
  (error) => {
    stopLoading()
    // useUserStore().logout()
    ElMessage.error(error.response?.data?.message || '网络错误')
    return Promise.reject(error)
  }
)

export default service
